package com.jfinal.shiro;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import com.jfinal.shiro.ShiroRealm.ShiroUser;

public class SH {

	public static boolean isAuth(){
		return SecurityUtils.getSubject().isAuthenticated();
	}
	
	public static Subject getSubject(){
		return SecurityUtils.getSubject();
	}
	
	public static ShiroUser getUser(){
		return (ShiroUser)getSubject().getPrincipal();
	}
	
	public static boolean hasRole(String roleName) {
		if (SecurityUtils.getSubject().hasRole("master")) {
			return true;
		}
		return SecurityUtils.getSubject().hasRole(roleName);
	}
	
	public static boolean hasRole(List<String> roleNames) {
		
		boolean[] bools = SecurityUtils.getSubject().hasRoles(roleNames);
		
		for (boolean b : bools) {
			if (b) {
				return b;
			}
		}
		
		return false;
	}
	
	public static String login(String userName,String password,boolean remember){
		String result = "success";
		UsernamePasswordToken token = new UsernamePasswordToken();
		token.setUsername(userName);
		token.setPassword(password.toCharArray());
		token.setRememberMe(remember);		
		try {
			SecurityUtils.getSubject().login(token);
		} catch (Exception e) {
			e.printStackTrace();
			result = "failure";
		} 
		return result;
	}
	
	public static void logout(){
		if(SecurityUtils.getSubject().isAuthenticated()){
			SecurityUtils.getSubject().logout();
		}		
	}
}
